package cn.dlc.com.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 邓立川
 * @date 2021/11/28 15:00
 * @desc 拦截请求，将获取到的认证相关的信息放到请求头里面，传递到下一个服务
 */
public class MyAuthFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 获取上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        // 获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 没有认证信息的话拦截
        if(! (authentication instanceof OAuth2Authentication)) {

            System.out.println("context.getRequest().getRequestURI(): " + context.getRequest().getRequestURI());
            System.out.println("context.getRequest().getRequestURL(): " + context.getRequest().getRequestURL());

            return null;
        }

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;

        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

        // 获取权限
        List<String> authorities = new ArrayList<>();
        userAuthentication.getAuthorities().
                stream().forEach(s->authorities.add(s.getAuthority()));

        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        // 拿到其他的请求参数
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String, Object> jsonToken = new HashMap<>(requestParameters);
        // 将解析后的用户的权限信息放到请求头里面。
        if(userAuthentication != null) {
            jsonToken.put("principal", userAuthentication.getName());
            jsonToken.put("authorities", authorities);
        }

        // 这个地方最好通过方式加密
        context.addZuulRequestHeader("json-token", JSON.toJSONString(jsonToken));

        System.out.println("zuulFilter..." + JSON.toJSONString(jsonToken) );


        return null;
    }
}
